package com.swlz.servlet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.swlz.R;
import com.swlz.config.AlipayConfig;
import com.swlz.vo.LoginUser;
import com.swlz.dto.MallCartDTO;
import com.swlz.entity.MallCart;
import com.swlz.entity.MallOrder;
import com.swlz.service.ConfigService;
import com.swlz.service.MallCartService;
import com.swlz.service.impl.ConfigServiceImpl;
import com.swlz.service.impl.MallCartServiceImpl;

@WebServlet("/mall-cart.let")
public class MallCartServlet extends HttpServletSupport {

	private MallCartService mallCartService = new MallCartServiceImpl();
	private static Logger log = LoggerFactory.getLogger(MallCartServlet.class);
	
	private ConfigService configService = new ConfigServiceImpl();
	
	public Object add(LoginUser user,HttpServletRequest request)throws Exception{
		log.debug("登录用户：{}",user);
		if(user==null){
			return R.msg(401, "用户未登录！");
		}
		Long productId = null;
		try{
			productId = Long.valueOf(request.getParameter("productId"));
		}catch(Exception ex){
			log.debug("获取产品编号错误!",ex);
			throw new Exception("获取产品编号错误!",ex);
		}
		log.info("添加到购物车的产品："+productId);
		MallCart mallCart = new MallCart();
		mallCart.setProductId(productId);
		mallCart.setUserId(user.getUserId());
		mallCartService.add(mallCart);
		return R.ok();
	}
	
	
	public Object delete(HttpServletRequest request)throws Exception{
		Long cartId = null;
		try{
			cartId = Long.valueOf(request.getParameter("cartId"));
			log.debug("++++"+cartId);
		}catch(Exception ex){
			log.debug("获取参数错误!",ex);
			throw new Exception("获取参数错误!",ex);
		}
		mallCartService.delete(cartId);
		return R.ok();
	}
	
	public String execute(HttpServletRequest request,LoginUser user)throws Exception {
		log.debug("qqqqqqqqqqqq");
		if(user == null){
			return "redirect:login1.jsp";
		}
		request.setAttribute("list", mallCartService.list(user.getUserId()));
		return "/mall/cart/list";
	}
	
	public String pay(HttpServletRequest request,LoginUser user)throws Exception {
		if(user == null){
			return "redirect:login.jsp";
		}
		
		log.debug(JSON.toJSONString(request.getParameterMap(),true));
		
		MallCartDTO dto = new MallCartDTO();
		
		dto.setUserId(user.getUserId());
		
		//获取收货地址Id
		dto.setAddressId(Long.valueOf(request.getParameter("addressId")));
		dto.setOrderMemo(request.getParameter("orderMemo"));
		
		//获取购买的产品id列表
		List<Long> productId = new ArrayList<Long>();
		for(String p : request.getParameterValues("productId")){
			productId.add(Long.valueOf(p));
		}
		dto.setProductId(productId);
		
		//获取购买的产品对应的数量列表
		List<Integer> cartNum = new ArrayList<>();
		for(String c : request.getParameterValues("cartNum")){
			cartNum.add(Integer.valueOf(c));
		}
		dto.setCartNum(cartNum);
		log.debug(JSON.toJSONString(dto,true));
		
		//添加订单,未支付状态
		MallOrder order = mallCartService.addOrder(dto);
		log.debug(JSON.toJSONString(order,true));
		
		//获取支付的配置信息
		AlipayConfig config = configService.getAlipayConfig();
		//发起支付
		AlipayClient alipayClient = new DefaultAlipayClient(config.gatewayUrl, config.appId, config.merchantPrivateKey, "json", config.charset, config.alipayPublicKey, config.signType);
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(config.returnUrl);
		alipayRequest.setNotifyUrl(config.notifyUrl);
		
		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = order.getOrderId().toString();
		//付款金额，必填
		String total_amount = order.getOrderMoney().toString();
		//订单名称，必填
		String subject = order.getOrderId().toString();
		//商品描述，可空
		String body = "商品";
		
		String json = "{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
		
		alipayRequest.setBizContent(json);
		AlipayResponse res = alipayClient.pageExecute(alipayRequest);
		request.setAttribute("body", res.getBody());
		
		return "/mall/cart/pay";
	}
	
}
